/**
 * 系统公共工具方法集合
*/

import { isObject } from 'lodash-es'
import type {
  App,
  Plugin,
  Component,
  ComputedOptions,
  MethodOptions,
} from 'vue'


/** 前端唯一键 */
export function getGuid() {
  return 'xxxx_zxxx_yxxx_xxxx'.replace(/[xy]/g, function (c) {
    const r = (Math.random() * 16) | 0
    const v = c === 'x' ? r : (r & 0x3) | 0x8
    return v.toString(16)
  })
}

/** 
 * 比较两个变量是否相等 (严格模式，不会进行类型转换)
 * @param var1            比较变量1
 * @param var2            比较变量2
 *  */
export function compareVar (var1: any, var2?: any) {
  return JSON.stringify(var1) === JSON.stringify(var2)
}

/**
 * 获取变量值类型
 * @param data            目标数据
 */
export function  getVarType(data: any): string {
  if (Array.isArray(data)) {
    return 'array'
  } else if (data === null) {
    return 'null'
  } else if (data === undefined) {
    return 'undefined'
  } else {
    return typeof data
  }
}



export const withInstall = <
  T extends Component<any, any, any, ComputedOptions, MethodOptions>,
>(
  component: T,
  alias?: string
) => {
  const comp = component as any
  comp.install = (app: App) => {
    app.component(comp.name || comp.displayName, component)
    if (alias) {
      app.config.globalProperties[alias] = component
    }
  }
  return component as T & Plugin
}


export function setTimeoutUtil (time: number, callback: Function) {
  const timeName = setTimeout(() => {
    callback()
    clearTimeout(timeName)
  }, time)
}

export function setIntervalUtil(time: number, callback: ()=> boolean) {
  const timeName = setTimeout(() => {
    if (callback()) {
      clearTimeout(timeName)
    }
  }, time)
}



/** 获取对象指定键的值 */
export function getObjectKeyValue(
  data: Record<string, any>,
  fields: Array<string>,
  defaultValue: any
) {
  if (fields.length === 1) {
    return data[fields[0]] ?? defaultValue
  } else {
    let curValue: any = undefined
    fields.forEach((field, index) => {
      if (index) {
        isObject(curValue)
          ? (curValue = curValue[field])
          : (curValue = undefined)
      } else {
        curValue = data[field]
      }
    })
    return curValue ?? defaultValue
  }
}
